#pragma once 

#include <iostream>
#include <string>
#include <cstdio>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>

class UdpClient{
  private:
    int sockfd;
    int server_port;
    std::string server_ip;
  public:
    UdpClient(int _port, std::string _ip):sockfd(-1), server_port(_port), server_ip(_ip)
    {}
    bool InitUdpClient()
    {
      sockfd = socket(AF_INET, SOCK_DGRAM, 0);
      if(sockfd == -1){
        std::cerr << "socket error" << std::endl;
        return false;
      }

      //不需要绑定(网络信息)
      return true;
    }
    void Start()
    {
      struct sockaddr_in peer;
      peer.sin_family = AF_INET;
      peer.sin_port = htons(server_port);
      peer.sin_addr.s_addr = inet_addr(server_ip.c_str());
      socklen_t len = sizeof(peer);

      std::string msg;
      std::cout << "Please Enter #" << std::endl;
      while(true){
        std::cin >> msg;

        ssize_t size = sendto(sockfd, msg.c_str(), msg.size(), 0, (const struct sockaddr*)&peer, len);
        if(size == -1){
          std::cerr << "sendto error" << std::endl;
        }

#define SIZE 128
        char buffer[SIZE];
        struct sockaddr_in tmp;
        socklen_t len = sizeof(tmp);
        ssize_t s = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&tmp, &len);
        if(s == -1){
          std::cerr << "recvfrom error" << std::endl;
        }

        buffer[s] = 0;
        std::cout << buffer << std::endl;
      }
    }
    ~UdpClient()
    {
      if(sockfd != -1) close(sockfd);
    }
};
